﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using cognysClient.CognyService;

namespace cognysClient.Admin
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                using (var client = new Service1Client())
                {
                    ddlTestGroup.DataSource = client.getTestGroup();
                    ddlTestGroup.DataValueField = "ID";
                    ddlTestGroup.DataTextField = "Name";
                    ddlTestGroup.DataBind();
                }
            }
            
        }

        /// <summary>
        /// Generates a username from the input data
        /// </summary>
        /// <param name="fname">Firstname</param>
        /// <param name="lname">Lastname</param>
        /// <param name="year">Social number</param>
        /// <returns>A username consisting of parts of the users' firstname, lastname and socialnumber</returns>
        private string GenerateUsername(string fname, string lname, string year)
        {
            var identifier = 0;
            int thirdFname = 2;
            int thirdLname = 2;
            if (fname.Length < 3)
            {
                thirdFname = 1;
            }
            if (lname.Length < 3)
            {
                thirdLname = 1;
            }

            var username = "" + fname[0] + fname[1] + fname[thirdFname] + lname[0] +
                lname[1] + lname[thirdLname] + year[0] + year[1] + identifier;

            bool check = true;
            do
            {
                var matches = Membership.FindUsersByName(username);
                if (matches.Count > 0)
                {
                    identifier++;
                    username = username.Substring(0, 8);
                    username += identifier;
                }
                else
                {
                    check = false;
                }
            } while (check);

            username.Replace(" ", string.Empty);
            return username.ToLower();
        }

        //Creates a user. Adds it to the aspnet db, and adds a Person object to the Rapp_DB.
        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            
                var firstname = tbFirstName.Text;
                var lastname = tbLastName.Text;
                var snumber = tbPersonal.Text;

                var username = GenerateUsername(firstname, lastname, snumber);
                string password = Guid.NewGuid().ToString().Substring(0, 5);
                var mcs = new MembershipCreateStatus();
                Membership.CreateUser(username, password, null, null, null, true, out mcs);

                if (ddlUserGroup.Text == "Vuxen")
                {
                    Roles.AddUserToRole(username, "User-vuxen");
                }
                else if (ddlUserGroup.Text == "Barn")
                {
                    Roles.AddUserToRole(username, "User-barn");
                }
                lblNewUserCreated.Text = "Ny användare skapad!";
                lblUserName.Text = "Användarnamn:";
                lblPassword.Text = "Lösenord:";
                lblUserNameAnswer.Text = username;
                lblPasswordAnswer.Text = password;

                using (var client = new Service1Client())
                {
                    Guid id = Guid.Parse(Membership.GetUser(username).ProviderUserKey.ToString());

                    var person = new Person();
                    person.ID = id;
                    person.Firstname = firstname;
                    person.Lastname = lastname;
                    person.SocialNumber = snumber;
                    client.SavePerson(person);

                    client.addPersonToTestgroup(id, Convert.ToInt32(ddlTestGroup.SelectedValue));

                    //creates an empty baseline and resultstate for the newly created user
                    Baseline bs = new Baseline();
                    bs.Person = id;
                    client.AddBaseLine(bs);
                    ResultState rs = new ResultState();
                    rs.Person = id;
                    client.AddResultState(rs);
                }
                tbFirstName.Text = "";
                tbLastName.Text = "";
                tbPersonal.Text = "";
           

        }
    }
}